package com.sxbbc.api.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxbbc.api.service.IBaseService;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.service.redis.RedisUtilsService;
import com.sxbbc.common.basics.service.solr.entity.Solrpage;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.dto.jz.SearchVo;
import com.sxbbc.common.core.enums.BusinessScopeEnums;
import com.sxbbc.common.core.enums.BusinessTypeEnums;
import com.sxbbc.common.core.enums.ProductStatusEnums;
import com.sxbbc.common.core.enums.ProductTypeEnums;
import com.sxbbc.common.core.mapper.jz.ProcMainMapper;
import com.sxbbc.common.core.service.system.solr.SolrproductService;
import com.sxbbc.common.core.service.system.solr.entity.SolrProductDto;
import com.sxbbc.common.core.utils.BasePage;

/**
 * 公用业务 接口服务实现类
 *
 * @author leehao
 * @date 2019-05-15 16:20
 */
@SuppressWarnings("all")
@Service
public class BaseServiceImpl implements IBaseService {

    @Autowired
    private SolrproductService solrProductService;
    @Autowired
    private BBusinessService businessService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private ICCollectBusService collectBusService;
    @Autowired
    private IProcMainService procMainService;
    @Autowired
    private RedisUtilsService redisUtilsService;
    @Autowired
    private ProcMainMapper procMainMapper;
    @Autowired
    private ICCustomerService customerService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private ICFootprintInfoService footprintInfoService;

    /**
     * 搜索商品
     */
    private static final int SEARCH_PRODUCT = 1;
    /**
     * 搜索商家
     */
    private static final int SEARCH_BUSINESS = 2;

    @Override
    public IPage<ProcMain> queryLikeList(Integer cid, BasePage<ProcMain> page) {
        //获取redis中二级分类ID的set集合
        IPage<ProcMain> pageInfo = new Page<ProcMain>();
        if (cid != null) {
            QueryWrapper<CFootprintInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("cid",cid);
            int count = footprintInfoService.count(wrapper);
            //cid不为空的时候去根据浏览记录
            if(count > 0){
                pageInfo = procMainMapper.queryCustomerLikeByFootPrint(page, cid);
            }else{
                //根据消费记录
                Set<String> secondSet = redisUtilsService.getSecondValue(String.valueOf(cid));
                if (!CollectionUtils.isEmpty(secondSet)) {
                    pageInfo = procMainMapper.queryCustomerLikeByBuyRecord(page,secondSet, cid);
                }else{
                    //查询默认的记录
                    pageInfo = procMainMapper.queryNormalCustomerLike(page);
                }
            }
        }
        CalcuUtils calUtil = CalcuUtils.getInstance();
        List<ProcMain> list = new ArrayList<>();
        //只有上架的商品与已审核的商品才允许显示
        for (ProcMain p : pageInfo.getRecords()) {
            if (p != null && calUtil.isEquals(p.getStatus(),ProductStatusEnums.SHELVES.getId())
                    && calUtil.isEquals(p.getExamineStatus(),ProductStatusEnums.HAS_CHECK.getId())) {
                list.add(p);
            }
        }
        pageInfo.setRecords(list);
        return pageInfo;
    }

    /**
     * 清除缓存元素
     * allEntries，表示是否需要清除缓存中的所有元素
     * 指定该属性值为true时，Spring会在调用该方法之前清除缓存中的指定元素
     */
    @CacheEvict(value = "bbcCache", allEntries = true, beforeInvocation = true)
    @Override
    public void refreshCache() {
    }

    @Override
    public Map<String, Object> handleSearchProductOrBusiness(SearchVo search,Integer cpage, Integer csize) {
        Map<String, Object> map = new HashMap<String, Object>(16);
        Solrpage<SolrProductDto> solrDto = null;
        CalcuUtils calUtil = CalcuUtils.getInstance();
        if (calUtil.isEquals(SEARCH_PRODUCT, search.getType())) {
            // 如果是搜索商品
            // 定义一个solr搜索对象
            SolrProductDto solrProductDto = new SolrProductDto();
            solrProductDto.setType(ProductTypeEnums.NORMAL.getId());
            // 设置solr的关键词即可，keyword=keyword+pname+descval
            //solrProductDto.setKeyword(search.getKey());
            solrProductDto.setPname(search.getKey());
            if (search.getBid() != null) {
                // bid不为空，是对店铺中的商品进行搜索
                solrProductDto.setBid(search.getBid());
            }
            // 页码(page)默认可设置为1
            solrDto = solrProductService.queryProduct(solrProductDto, search.getSortType(), search.getSortDesc(), cpage, csize);
            //处理店铺类型标记
            if (!CollectionUtils.isEmpty(solrDto.getList()) && solrDto.getList().size() > 0) {
                for (SolrProductDto pro : solrDto.getList()) {
                    BBusiness bBusiness = businessService.getById(pro.getBid());
                    if (calUtil.isEquals(bBusiness.getBType(),BusinessTypeEnums.OWN_BUSINESS.getId())) {
                        pro.setbTypeName(BusinessTypeEnums.getName(bBusiness.getBType()));
                    }
                }
            }
            map.put("product", solrDto);
        } else if (calUtil.isEquals(SEARCH_BUSINESS, search.getType())) {
            // 如果是搜索商家
            if (StringUtils.isNotBlank(search.getKey())) {
                QueryWrapper<BBusiness> ew = new QueryWrapper<>();
                ew.eq("on_off",BusinessScopeEnums.ONLINE.getId()).
                        like(true,"nick_name_on",search.getKey());
                List<BBusiness> businessList = businessService.list(ew);
                for (BBusiness business : businessList) {
                    //部分字段置空
                    business.setPayWord(null);
                    business.setScale(null);
                    business.setCid(null);
                    business.setRyToken(null);
                    //设置店铺被收藏的数量
                    QueryWrapper collectQuery = new QueryWrapper();
                    collectQuery.eq("bid",business.getId());
                    collectQuery.eq("status",StaticUtils.STATUS_YES);
                    business.setCollect(collectBusService.count(collectQuery));
                    collectQuery.eq("status", ProductStatusEnums.SHELVES.getId());
                    collectQuery.eq("pro_type", ProductTypeEnums.NORMAL.getId());
                    business.setProNum(procMainService.count(collectQuery));
                    //设置店铺的类型名称
                    if (calUtil.isEquals(business.getBType(),BusinessTypeEnums.OWN_BUSINESS.getId())) {
                        business.setBTypeName(BusinessTypeEnums.OWN_BUSINESS.getName());
                    }
                }
                map.put("business",businessList);
            }
        }
        return map;
    }

	@Override
	public Map<String, Object> getShareMsg(Integer cid, Integer type, String data) {
		Map<String, Object> map = new HashMap<String, Object>();
		CCustomer customer = customerService.getById(cid);
		if (customer == null) {
			throw new ThrowJsonException("分享失败");
		}
		switch (type) {
		case StaticUtils.SHARE_PRODUCT:
			ProcMain proMain = procMainService.selectOneByProCode(data);
			if (proMain != null) {
				map.put("imgUrl", proMain.getProUrl());
				map.put("title", proMain.getProName());
				map.put("desc", proMain.getProDesc());
				map.put("linkUrl", "http://h5.danongkj.cn/#/pages/shopping/shop_details?id="+data);
			}
			break;
		case StaticUtils.SHARE_BUSINESS:
			BBusiness business = businessService.getById(Integer.parseInt(data));
			if (business != null) {
				map.put("imgUrl", business.getHeadUrl());
				map.put("title", business.getNickNameOn());
				map.put("desc", "");
				map.put("linkUrl", "http://h5.danongkj.cn/#/pages/shopping/store?id="+data);
			}
			break;
		case StaticUtils.SHARE_QRURL:
			// 二维码分享，必须要用户信息
			map.put("imgUrl", customer.getHeadurl());
			map.put("title", customer.getNickName());
			map.put("desc", "买卖就上君凤煌，铸就人生新辉煌。天天领红包，每天享分红。");
			map.put("linkUrl", "http://h5.danongkj.cn/?from=singlemessage#/pages/share/referrer?inviteCode="+customer.getInviteCode());
			break;
		case StaticUtils.SHARE_GROUP:
			// 团购分享
			List<OrderDetail> detailList = orderDetailService.listByOrderCode(String.valueOf(data));
			if (detailList == null || detailList.size() <= 0) {
				throw new ThrowJsonException("分享失败");
			}
			OrderDetail detail = detailList.get(0);
			String desc = detail.getProName();
			ProcMain proc = procMainService.getById(detail.getProId());
			if (proc != null) {
				desc = proc.getProDesc();
			}
			map.put("imgUrl", detail.getProUrl());
			map.put("title", detail.getProName());
			map.put("desc", desc);
			map.put("linkUrl", "http://h5.danongkj.cn/?#/pages/shopping/group/group_share?code="+String.valueOf(data));
			break;
		default:
			break;
		}
		map.put("inviteCode", customer.getInviteCode());
		return map;
	}
}
